require 'rubygems'
require 'watir'
require 'product'

class WebClient
  LOGIN_URL = "http://10.200.106.232/zencart/admin/login.php"
  CATEGORY_URL = "http://10.200.106.232/zencart/admin/categories.php?cPath=&action=new_category"
  SUB_CATEGORY_URL = "http://10.200.106.232/zencart/admin/categories.php?cPath=%s&action=new_category"
  PRODUCT_URL = "http://10.200.106.232/zencart/admin/categories.php?cPath=%s_%s"

  def initialize
    @ie = Watir::IE.new
    @ie.speed = :fast
	@count = 0
  end

  def login
    @ie.goto LOGIN_URL
    @ie.text_field(:name, 'admin_name').set('admin')
    @ie.text_field(:name, 'admin_pass').set('123456')
    @ie.button(:name, 'submit').click
  end

  def add_category(category)
    @ie.goto CATEGORY_URL
    @ie.text_field(:name, 'categories_name[2]').set(category.name)
    @ie.button(:src, /button_save/).click
    ss = @ie.url.split('=')
    if ss.length != 3
      raise "create category failed for " + category.name
    end
    category_id = ss[2]
    category.sub_categories.each do |sub_category|
      add_sub_category(category_id, sub_category)
    end
  end

  def add_sub_category(category_id, sub_category)
    @ie.goto(SUB_CATEGORY_URL % category_id)
    @ie.text_field(:name, 'categories_name[2]').set(sub_category.name)
    @ie.button(:src, /button_save/).click
    ss = @ie.url.split('=')
    if ss.length != 3
      raise "create sub category failed for " + sub_category.name
    end
    sub_category_id = ss[2]
    sub_category.products.each do |product|
      add_product(category_id, sub_category_id, product)
    end
  end

  def add_product(category_id, sub_category_id, product)
    @ie.goto(PRODUCT_URL % [category_id, sub_category_id])
    @ie.form(:name, "newproduct").submit
    @ie.text_field(:name, "products_name[2]").set(product.name)
    if product.price
      @ie.text_field(:name, "products_price").set(product.price)
    end
    if product.content
      @ie.frame(:index, 1).document.body.innertext = product.content
    end
    if product.no
      @ie.text_field(:name,"products_model").set(product.no)
    end

    @ie.text_field(:name, "products_quantity").set(product.quantity)
    @ie.select_list(:name, "img_dir").select("products")
    if product.pic
      @ie.text_field(:name, "products_image_manual").set(product.pic)
    end
    @ie.button(:src, /button_preview/).click
    @ie.button(:src, /button_insert/).click
	@count += 1
	puts "added product " + @count.to_s
  end
end
